<!--
 * @Author: lizijian
 * @Date: 2024-03-21 10:00:57
 * @LastEditTime: 2024-03-21 18:22:19
 * @FilePath: \client\src\components\global\yppopover\yppopover.vue
 * @Description: 弹出框组件
-->
<template>
	<div ref="popover">
		<div class="cursor-pointer">
			<slot name="reference"></slot>
		</div>
		<Teleport to="body">
			<div
				class="absolute mt-2 p-2 bg-orange-300 rounded"
				ref="popoverContent"
				:style="popoverStyle"
				v-show="modelValue"
			>
				<div class="w-40">
					<slot name="popover-content"></slot>
				</div>
			</div>
		</Teleport>
	</div>
</template>
<script setup>
	import {
		onMounted,
		ref,
		reactive,
		watch,
	} from 'vue'
	const props = defineProps(['modelValue'])
	const emits = defineEmits(['update:modelValue'])
	const popover = ref(null)
	const popoverContent = ref(null)
	const popoverStyle = reactive({
		left: 0,
		top: 0,
	})
	watch(
		() => props.modelValue,
		(newVal) => {
			if (!newVal) {
				popoverContent.value.removeEventListener('mouseleave', null)
			} else {
				popoverContent.value.addEventListener('mouseleave', () => {
					emits('update:modelValue',false)
				})
			}
		}
	)
	onMounted(() => {
		const { top, left, height } = popover.value.getBoundingClientRect()
		popoverStyle.left = `${left}px`
		popoverStyle.top = `${top + height}px`
		popoverStyle.transform = 'translateX(-50%)'
	})
</script>
